using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;
using System.Diagnostics;
using IWCommunity.Common;

namespace IWCommunity.Blogs.WebControls
{
    public class CategoriesList : List
    {
        private bool _includePostCount = true;

        public bool IncludePostCount
        {
            get { return _includePostCount; }
            set { _includePostCount = value; }
        }

        public CategoriesList()
        {
            ListName = "Categories";
        }

        protected override System.Xml.XmlDocument BuildDocument()
        {
            try
            {
                XmlDocument oDoc = base.BuildDocument();

                if (IncludePostCount)
                {
                    XmlNodeList oCats = oDoc.SelectNodes("rows/row");
                    foreach (XmlElement oCat in oCats)
                    {
                        int iCount = CalculatePostCount(oCat.SelectSingleNode("Title").InnerText);
                        oCat.SetAttribute("PostCount", iCount.ToString());
                    }
                }

                return oDoc;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);

                XmlDocument oError = new XmlDocument();
                oError.LoadXml(string.Format("<Error>{0}</Error>", ex.Message));
                return oError;
            }
        }

        protected virtual int CalculatePostCount(string categoryTitle)
        {
            SPList oPosts = Web.Lists["Posts"];

            SPQuery oQuery = new SPQuery();
            oQuery.ViewFields = "<FieldRef Name='PostCategory'/>";
            oQuery.Query = string.Format("<Where><Eq><FieldRef Name='PostCategory'/><Value Type='Text'>{0}</Value></Eq></Where>", categoryTitle);

            return oPosts.GetItems(oQuery).Count;
        }
    }
}
